package com.wow.wa.bill.serivce;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.wow.wa.bill.serivce.vo.DateRange;
import com.wow.wa.bill.util.Args;
import com.wow.wa.bill.util.Args.DBSchema;
import com.wow.wa.bill.util.DBHelper;
import com.wow.wa.bill.util.VoConvertComponent;
import com.wow.wa.bill.util.VoConvertComponentImpl;
import com.wow.wa.bill.vo.Bill;
import com.wow.wa.bill.vo.BroadcastRec;
import com.wow.wa.bill.vo.Card;
import com.wow.wa.bill.vo.CardType;
import com.wow.wa.bill.vo.Category;
import com.wow.wa.util.CommonUtils;

public class BillServiceImpl implements BillService {
	private static final String TAG = "BillServiceImpl";
	private CommonComent common;
	private VoConvertComponent componet;
	private Context ct;
	

	// private static DBHelper dbHelper;

	public BillServiceImpl(Context context) {
		// dbHelper = new DBHelper(context);
		componet = new VoConvertComponentImpl();
		common = new CommonComentImpl(context);
		this.ct = context;
	}

	@Override
	public List<Bill> getBill(Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "SELECT * FROM " + Args.DBSchema.BILL_TABLE_NAME
				+ " order by dueDate ASC";
		Cursor cursor = db.rawQuery(sql, null);

		List<Bill> bills = componet.getObjForm(cursor, Bill.class);
		db.close();
		return bills;
	}

	public void insertBill(Bill bill, Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues map = componet.contentValueFromVo(bill);
		db.insert(Args.DBSchema.BILL_TABLE_NAME, "", map);
		db.close();
	}

	@Override
	public void deleteBill(String tx, Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(Args.DBSchema.BILL_TABLE_NAME, "tx=? ", new String[] { tx });
		// db.delete(Args.DBSchema.ANIMAL_TABLE_NAME, whereClause, whereArgs);

		db.close();

	}

	@Override
	public void updateBill(Bill bill, String tx, Context context)
			throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		db.update(Args.DBSchema.BILL_TABLE_NAME,
				componet.contentValueFromVo(bill), "tx=?", new String[] { tx });
		// TODO Auto-generated method stub

	}

	@Override
	public List<Bill> getBillWithNoPaid(Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "SELECT * FROM " + Args.DBSchema.BILL_TABLE_NAME
				+ " where isPayed<>'Y' order by dueDate ASC";
		Cursor cursor = db.rawQuery(sql, null);

		List<Bill> bills = componet.getObjForm(cursor, Bill.class);
		db.close();
		return bills;
	}

	@Override
	public List<Bill> getBillOverDay(Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "SELECT * FROM " + Args.DBSchema.BILL_TABLE_NAME
				+ " where isPayed='N' and dueDate<" + CommonUtils.getDate()
				+ " order by dueDate ASC";
		Cursor cursor = db.rawQuery(sql, null);

		List<Bill> bills = componet.getObjForm(cursor, Bill.class);
		db.close();
		return bills;
	}

	@Override
	public List<Category> getCategorys(Context context) {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "	select  * from category order by _id desc";
		Cursor cursor = db.rawQuery(sql, new String[] {});

		List<Category> categorys = componet.getObjForm(cursor, Category.class);
		db.close();
		return categorys;
	}

	@Override
	public List<String> getStringPayTyp(Context context) {

		final List<String> returnObj = new ArrayList<String>();
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(Args.DBSchema.CARD_TABLE_NAME,
				new String[] { "name" }, null, null, null, null, "_id desc");
		// String[] title = new String[cursor.getCount()];

		while (cursor.moveToNext()) {
			// Category category = new Category();
			// category.setId(cursor.getInt(0));
			// category.setName(cursor.getString(1));
			// title[i++] = cursor.getString(0);
			returnObj.add(cursor.getString(0));

		}
		cursor.close();
		return returnObj;
	}

	@Override
	public List<String> getStringCategorys(Context context) {

		final List<String> returnObj = new ArrayList<String>();
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(DBSchema.CATEGORY_TABLE_NAME,
				new String[] { "name" }, null, null, null, null, null);

		while (cursor.moveToNext()) {
			// Category category = new Category();
			// category.setId(cursor.getInt(0));
			// category.setName(cursor.getString(1));
			returnObj.add(cursor.getString(0));

		}
		cursor.close();
		return returnObj;
	}

	@Override
	public List<Bill> getBill(String payType, Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "SELECT * FROM " + Args.DBSchema.BILL_TABLE_NAME
				+ " WHERE TYPE=? order by dueDate ASC";
		Cursor cursor = db.rawQuery(sql, new String[] { payType });

		List<Bill> bills = componet.getObjForm(cursor, Bill.class);
		db.close();
		return bills;
	}

	@Override
	public void insertCard(Card card, Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues map = componet.contentValueFromVo(card);
		db.insert(Args.DBSchema.CARD_TABLE_NAME, "", map);
		db.close();

	}

	@Override
	public void updateBillToPayed(Bill bill, Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		bill.setIsPayed(Args.Common.STRING_Y);
		ContentValues map = componet.contentValueFromVo(bill);
		db.update(Args.DBSchema.BILL_TABLE_NAME, map, "_id=?",
				new String[] { bill.get_id() + "" });
		db.close();

	}

	@Override
	public void deeteBill(Bill bill, Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(Args.DBSchema.BILL_TABLE_NAME, "_id=?",
				new String[] { bill.get_id() + "" });
		db.close();

	}

	@Override
	public void updateBillToNoPayed(Bill bill, Context context)
			throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		bill.setIsPayed(Args.Common.STRING_N);
		ContentValues map = componet.contentValueFromVo(bill);
		db.update(Args.DBSchema.BILL_TABLE_NAME, map, "_id=?",
				new String[] { bill.get_id() + "" });
		db.close();

	}

	@Override
	public String stringByCountTotalMoneyWithNoPay(List<Bill> bills)
			throws Exception {

		Long i = (long) 0.0;
		for (Bill b : bills) {
			if (StringUtils.equals(b.getIsPayed(), Args.Common.STRING_Y)) {
				continue;
			}
			if (StringUtils.isBlank(b.getDollar())) {
				continue;
			}
			i += Long.parseLong(b.getDollar());

		}

		// TODO Auto-generated method stub
		return common.stringtoMoney(i.toString());
	}

	@Override
	public String stringBycountTotalMoneyWithPay(List<Bill> bills)
			throws Exception {
		Long i = (long) 0.0;
		for (Bill b : bills) {
			if (StringUtils.equals(b.getIsPayed(), Args.Common.STRING_N)) {
				continue;
			}
			if (StringUtils.isBlank(b.getDollar())) {
				continue;
			}
			i += Long.parseLong(b.getDollar());

		}

		// TODO Auto-generated method stub
		return common.stringtoMoney(i.toString());
	}

	@Override
	public void updateBill(Bill bill, Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		ContentValues map = componet.contentValueFromVo(bill);
		db.update(Args.DBSchema.BILL_TABLE_NAME, map, "_id=?",
				new String[] { bill.get_id() + "" });
		db.close();

	}

	@Override
	public DateRange getRangDay(Card card, Context context) {
	//	final String dayOfPeriod = card.getInDate();
		final DateRange range = new DateRange();
		range.setBegin("0000/00/00");
		range.setEnd("9999/99/99");
		return range;
//		try {
//			if (dayOfPeriod == null || StringUtils.isBlank(dayOfPeriod)) {
//				range.setEnd("9999/99/99");
//				return range;
//			}
//
//			// int dayOfPeroiod = Integer.parseInt(dayOfPeriod);
//			// int dd = Integer.parseInt(CommonUtils.getDateDay());
//			// final DateRange range = new DateRange();
//			// range.setBegin("0000/00/00");
//
//			Date paydate = CommonUtils.getDateAsDate(dayOfPeriod);// 繳費日期
//			final Date nowDate = CommonUtils.getDateAsDate(CommonUtils
//					.getDate());// 今天
//
//			Calendar calendar = Calendar.getInstance();
//			Boolean isNeedUpdate = false;
//			while (paydate.before(nowDate)) {
//				isNeedUpdate = true;
//				calendar.setTime(paydate);
//				calendar.add(Calendar.MONTH, +1);
//				paydate = calendar.getTime();
//			}
//			range.setEnd(CommonUtils.getDate(paydate));
//			card.setInDate(CommonUtils.getDate(paydate));
//
//			if (isNeedUpdate) {
//				updateCard(card, context);
//			}
//		} catch (Exception e) {
//			Log.v(TAG, " getRangDay error e=" + e);
//		}
//
//		return range;Ø

	}

	@Override
	public List<Bill> getBill(String type, String start, String end,
			Context context) throws Exception {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "select * from bill where dueDate>=? and (dueDate <=? or dueDate=='') and isPayed<>? and type=? order by dueDate ASC ";
		Cursor cursor = db
				.rawQuery(sql, new String[] { start, end, "Y", type });

		Log.v(TAG, "start="+start+"\n end="+end+"\n type="+type+"\n");
		List<Bill> bills = componet.getObjForm(cursor, Bill.class);
		db.close();
		return bills;

	}

	@Override
	public List<Card> getCard(Context context) {
		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "SELECT * FROM CARD ORDER BY _ID DESC";
		Cursor cursor = db.rawQuery(sql, null);

		List<Card> cards = componet.getObjForm(cursor, Card.class);
		db.close();
		return cards;
	}

	@Override
	public List<Category> getCategorys(String id, Context context) {

		DBHelper dbHelper = new DBHelper(context);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "	select  * from category where cardId=? order by _id desc";
		Cursor cursor = db.rawQuery(sql, new String[] { id });

		List<Category> categorys = componet.getObjForm(cursor, Category.class);
		db.close();
		return categorys;

	}

	@Override
	public void updateCard(Card card, Context context) {
		try {
			DBHelper dbHelper = new DBHelper(context);
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			ContentValues map = componet.contentValueFromVo(card);
			db.update(Args.DBSchema.CARD_TABLE_NAME, map, "_id=?",
					new String[] { card.get_id() + "" });
			db.close();
		} catch (Exception e) {
			Log.v(TAG, "UPDATE ERROR =" + e);
		}

	}

	@Override
	public String getCardTypeName(String CardId) {
		DBHelper dbHelper = new DBHelper(this.ct);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "	select * from CardType where _id=?";
		Cursor cursor = db.rawQuery(sql, new String[] { CardId });

		List<CardType> categorys = componet.getObjForm(cursor, CardType.class);
		db.close();
		return categorys.get(0).getName();
	}

	@Override
	public String getCategoryName(String id) {

		if (StringUtils.isBlank(id)) {
			return StringUtils.EMPTY;
		}

		DBHelper dbHelper = new DBHelper(this.ct);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "	select * from Category where _id=?";
		Cursor cursor = db.rawQuery(sql, new String[] { id });

		List<Category> categorys = componet.getObjForm(cursor, Category.class);
		db.close();
		if (categorys.isEmpty()) {

			return StringUtils.EMPTY;
		} else {
			return categorys.get(0).getName();
		}

	}

	@Override
	public boolean hasBroadCastRec() {

		DBHelper dbHelper = new DBHelper(this.ct);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "SELECT * FROM BROADCASTREC where yyymmdd=?";

		Cursor cursor = db
				.rawQuery(sql, new String[] { CommonUtils.getDate() });
		
		List<BroadcastRec> broadcastRecs = componet.getObjForm(cursor,
				BroadcastRec.class);
		db.close();

		if (broadcastRecs.isEmpty()) {
			return true;
		} else {
			return false;
		}

	}

	@Override
	public void insertBroadCastRec() {

		try {

			DBHelper dbHelper = new DBHelper(this.ct);
			SQLiteDatabase db = dbHelper.getWritableDatabase();

			BroadcastRec rec = new BroadcastRec();
			rec.setYyymmdd(CommonUtils.getDate());
			rec.setHhmmss(CommonUtils.getTime());

			ContentValues map = componet.contentValueFromVo(rec);
			db.insert(Args.DBSchema.BROADCASTREC, "", map);
			db.close();
		} catch (Exception e) {
			Log.e(TAG, "insertBroadCastRec");
		}

	}

	@Override
	public Card getCardByBill(Bill bill) {
		DBHelper dbHelper = new DBHelper(this.ct);
		SQLiteDatabase db = dbHelper.getReadableDatabase();

		String sql = "SELECT * FROM CARD WHERE _id=? ORDER BY _ID DESC";
		Cursor cursor = db.rawQuery(sql, new String[]{bill.getType()});

		List<Card> cards = componet.getObjForm(cursor, Card.class);
		db.close();
		
		return cards.get(0);
	}

	@Override
	public void insertBillAndNotify(Bill bill) {
		// TODO Auto-generated method stub
		
	}

}
